﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SuperKit
{
    class ZipPackDirectory : CommandExecutor
    {
        class ZipThread : CommandThread
        {
            public ZipPackDirectory Parent { get; }
            public string FilePath { get; }

            public ZipThread(string path, ZipPackDirectory parent)
            {
                Parent = parent;
                FilePath = path;
            }


            public override void Execute()
            {
                Pack(new DirectoryInfo(FilePath));
            }



            private void Pack(DirectoryInfo dir)
            {
                var zipname = dir.Name + ".zip";
                var zippath = Path.Combine(dir.Parent.FullName, zipname);
                if (File.Exists(zippath))
                {
                    Parent.Flush("ZIP已经存在：{0}", zippath);
                    return;
                }
                else
                {
                    Parent.Flush("压缩ZIP：{0}", zippath);
                }
                string cmd = string.Format("a -mx=0 \"{0}\" \"{1}\"", zippath, dir.FullName);
                //Parent.Flush("Cmd：{0}", cmd);
                string result = ShellKit.ExecuteZip(cmd);
                Parent.Flush(result);
            }
        }

        public int TYPE_DIRECTORY = 0; // 直接将该目录下面的子目录分别打包
        public int TYPE_CATALOG = 1; // 该目录下面的子目录是Catalog，Catalog下面的子目录分别打包。

        public ZipPackDirectory(ArgReader arg, IExecutorOwner form, string fpath) : base(arg, form, fpath)
        {

        }

        public override void Execute()
        {
            base.Execute();
            int type = Arg.TypeId;

            if (type == TYPE_DIRECTORY)
            {
                OnDirectory(FilePath);
            }
            else if (type == TYPE_CATALOG)
            {
                OnCatalog();
            }

            StartThread();
        }

        protected override void ExecuteCurrentThread()
        {
            base.ExecuteCurrentThread();

        }

        private void OnCatalog()
        {
            DirectoryInfo dir = new DirectoryInfo(FilePath);
            var dirs = dir.GetDirectories();
            foreach (var i in dirs)
            {
                OnDirectory(i.FullName);
            }
        }

        private void OnDirectory(string filePath)
        {
            DirectoryInfo dir = new DirectoryInfo(filePath);
            var dirs = dir.GetDirectories();
            foreach (var i in dirs)
            {
                AddThreadItem(new ZipThread(i.FullName, this));
            }
        }
    }
}
